<?php

namespace App\System\Order\Repositories;

use App\Exceptions\Customize\ParamsException;
use App\Module\Api\Controllers\Request\OrderSubmitRequest;
use App\Module\Api\Controllers\Request\QueryRequest;
use App\Module\Api\Controllers\Request\TableRequest;
use App\Module\Api\Controllers\Request\TableWhereRequest;
use App\System\Base\Helpers\Traits\SinglePattern;
use App\System\Base\Repositories\Repository;
use App\System\Base\Services\TokenService;
use App\System\Cis\Repositories\CisUserAddressRepository;
use App\System\Coupon\Repositories\CouponUserRepository;
use App\System\Goods\Model\GoodsInfo;
use App\System\Goods\Repositories\GoodsAlbumRepository;
use App\System\Goods\Repositories\GoodsInfoRepository;
use App\System\Order\Model\OrderGoods;
use App\System\Order\Model\OrderInfo;
use Illuminate\Support\Facades\DB;

class OrderGoodsEvaluateRepository extends Repository
{
    use SinglePattern;

    /**
     * 获取订单数和订单额
     * @return array
     */
    public function getData(){
        //今日订单数
        $todayCount = OrderInfo::where('created_at','>=',date('Y-m-d',time()))->count();
        //本月订单数
        $monthCount = OrderInfo::where('created_at','>=',date('Y-m-01',time()))->count();
        //今日订单额
        $todayCash = OrderInfo::where('created_at','>=',date('Y-m-d',time()))->sum('order_amount');
        //本月订单额
        $monthCash = OrderInfo::where('created_at','>=',date('Y-m-01',time()))->sum('order_amount');
        $data = [
            'todayCount' => $todayCount,
            'monthCount' => $monthCount,
            'todayCash' => $todayCash,
            'monthCash' => $monthCash
        ];
        return $data;
    }

    /**
     * @param string $keyword
     * @param string $startTime
     * @param string $endTime
     * @param string $status
     * @param bool $getAll false:获取分页数据 trueh：获取全部数据
     * @return mixed
     */
    public function getList($keyword='',$startTime='',$endTime='',$status='',$getAll=false)
    {
        if($getAll){
            $data = OrderInfo::when($status, function ($query) use ($status) {
                    return $query->where('status', $status);
                })
                ->when($keyword,function($query)use($keyword){
                    return $query->where('order_sn','like','%'.$keyword.'%');
                })
                ->when($startTime,function ($query)use($startTime){
                    return $query->where('created_at','>=',$startTime);
                })
                ->when($endTime,function ($query)use($endTime){
                    return $query->where('created_at','<=',$endTime.' 23:59:59');
                })
                ->orderBy('created_at', 'desc')
                ->get();
        }else{
            $data = OrderInfo::when($status, function ($query) use ($status) {
                return $query->where('status', $status);
            })
                ->when($keyword,function($query)use($keyword){
                    return $query->where('order_sn','like','%'.$keyword.'%');
                })
                ->when($startTime,function ($query)use($startTime){
                    return $query->where('created_at','>=',$startTime);
                })
                ->when($endTime,function ($query)use($endTime){
                    return $query->where('created_at','<=',$endTime.' 23:59:59');
                })
                ->orderBy('created_at', 'desc')
                ->paginate();
        }
        return $data;
    }

    /*
     * 订单详情
     */
    public function getDetail($id)
    {
        if(!$id){
            return false;
        }
        $data = OrderInfo::with(['orderGoods.goods','finance.pay'])
        ->where('id',$id)->first();
//        dd($data);die;
        return $data;
    }

    /*
     *  修改信息
     */
    public function updateData($id,$updata){
        if(!$id){
            return false;
        }
        $order = OrderInfo::find($id);
        if(isset($updata['shipping_name'])){
            $order->shipping_name = $updata['shipping_name'];
        }
        if(isset($updata['shipping_code'])){
            $order->shipping_code = $updata['shipping_code'];
        }
        if(isset($updata['admin_message'])){
            $order->admin_message = $updata['admin_message'];
        }
        if(isset($updata['status'])){
            $order->status = $updata['status'];
        }
        if(isset($updata['shipping_time'])){
            $order->shipping_time = $updata['shipping_time'];
        }
        $bool = $order->save();
        if($bool){
            $msg = '操作成功！';
        }else{
            $msg = '操作失败！';
        }
        return ['data' => $bool, 'message' => $msg];
    }

    /**
     * 订单生成总入口
     * @param OrderSubmitRequest $orderSubmitRequest
     * @param $user_id
     */
    public function generateOrder(OrderSubmitRequest $orderSubmitRequest)
    {
        DB::beginTransaction();
        $user_id = TokenService::getUserId();
        $master_id = TokenService::getMasterId();
        $user_address = CisUserAddressRepository::getInstance();
        $address_info = $user_address->getDetail($orderSubmitRequest->contactsId,$master_id);
        if(!$address_info)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '收货地址错误',
            ]);
        }
        $goods = GoodsInfoRepository::getInstance();
        $goods_info = $goods->getDetail($orderSubmitRequest->goodsId);
        if(!$goods_info || $goods_info->status != 1)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '产品不存在或已下架',
            ]);
        }

        if($goods_info->stock < 1)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '产品库存不足',
            ]);
        }
        $pay_amount = $goods_info->member_price;
        $user_coupon_id = 0;
        if($orderSubmitRequest->shoppingId)
        {
            $coupon =  CouponUserRepository::getInstance();
            $coupon_info = $coupon->getOne($orderSubmitRequest->shoppingId,$user_id);
            if(!$coupon_info)
            {
                throw new ParamsException([
                    'error_code' => '1000',
                    'message'    => '购物券不存在',
                ]);
            }
            if($coupon_info->status !=0 || $coupon_info->expire_time < date("Y-m-d H:i:s"))
            {
                throw new ParamsException([
                    'error_code' => '1000',
                    'message'    => '购物券已过期或已使用',
                ]);
            }
            $res = $coupon->update(['status'=>1],$coupon_info->id);//更新购物券状态为已经使用
            if(!$res)
            {
                throw new ParamsException([
                    'error_code' => '1000',
                    'message'    => '购物券更新出错',
                ]);
            }
            $user_coupon_id = $orderSubmitRequest->shoppingId;
            $pay_amount = ($pay_amount - $coupon_info->amount) < 0 ? 0 : ($pay_amount - $coupon_info->amount);
        }
        //更新产品库存
        $res = GoodsInfo::where('id',$orderSubmitRequest->goodsId)->decrement('stock',1);//减小库存
        if(!$res)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '产品库存更新出错',
            ]);
        }
        //生成订单
        $set = [
            'order_sn'=>$this->generateOrderSn(),
            'type'=>1,
            'status'=>1,
            'consignee'=>$address_info->consignee,
            'address'=>$address_info->address_info,
            'mobile' => $address_info->mobile,
            'order_amount' => $goods_info->member_price,
            'pay_amount' =>$pay_amount,
            'user_message' => $orderSubmitRequest->userMessage ? $orderSubmitRequest->userMessage : '',
            'user_id' => $user_id,
            'user_coupon_id' => $user_coupon_id,
            'merchant_id'=> 0
        ];
        $order = OrderInfo::create($set);
        //生成订单产品
        if(!isset($order->id) || !$order->id)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '订单生成失败',
            ]);
        }
        $set = [
            'goods_name'=>$goods_info->name,
            'goods_num'=>1,
            'market_price'=>$goods_info->market_price,
            'cost_price' => $goods_info->cost_price,
            'member_price' => $goods_info->member_price,
            'order_id' => $order->id,
            'goods_id' => $goods_info->id
        ];
        $order_goods = OrderGoods::create($set);
        if(!isset($order_goods->id) || !$order_goods->id)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '订单生成失败',
            ]);
        }
        DB::commit();
        return $order->id;
    }

    /**
     * API 获取记录列表
     * @param TableRequest $request
     * @param TableWhereRequest $tableWhereRequest
     * @param $user_id
     * @return mixed
     */
    public function getApiList(TableRequest $request,TableWhereRequest $tableWhereRequest,$user_id)
    {
        $status = $tableWhereRequest->status;
        $data = OrderInfo::where("user_id",$user_id)
            ->when($status,function($query) use($status){
               return $query->where('status',$status);
            })
            ->orderBy($request->orderBy,$request->orderType)
            ->paginate($request->limit,['*'],'page',$request->page);
        $goods_ids = [];
        foreach ($data as $val)
        {
            $goods_ids[] = $val->goods_id;
        }
        $goods_album = GoodsAlbumRepository::getInstance();

        foreach($data as $v) {
            $item = [];
            $item['id'] = $v->id;
            $item['totalCash'] = $v->order_amount;
            $item['status'] = $v->status;
            $goods_info = OrderGoods::where('order_id',$v->id)->first();
            $album = $goods_album->getInIds([$goods_info->goods_id]);
            $orderGoodses = [
                'id'=>$goods_info->id,
                'goods_id'=>$goods_info->goods_id,
                'name' => $goods_info->goods_name,
                'cash' => $goods_info->member_price,
                'number' => $goods_info->goods_num,
                'imagePath'=>$album[$goods_info->goods_id]
            ];
            $merchant = ['id'=>0,'name'=>"创客中心","orderGoodses"=>$orderGoodses];
            $item['merchant'] = $merchant;
            $return['orders'][] = $item;
        }
        $return['total'] =$data->total();
        return $return;
    }

    /**
     * 生成订单编号
     */
    public function generateOrderSn()
    {
        return date("YmdHis").mt_rand(1000,9999);
    }

    /**
     * API 获取订单详细
     * @param $id
     * @param $user_id
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    public function getOne($id,$user_id)
    {
        $order_info = OrderInfo::with(['orderGoods'])
        ->where('id',$id)
        ->when($user_id,function ($query)use($user_id){
            return $query->where('user_id',$user_id);
        })
        ->first();
        $item = [];
        if($order_info)
        {
            $item['id'] = $order_info->id;
            $item['totalCash'] = $order_info->order_amount;
            $item['status'] = $order_info->status;
            $item['payAmount'] = $order_info->pay_amount;
            $item['orderSn'] = $order_info->order_sn;
            $item['shoppingCardCash'] = $order_info->order_amount - $order_info->pay_amount;
            $item['paymentTime'] = $order_info->pay_time;
            $item['deliveryTime'] = $order_info->shipping_time;
            $item['receiveTime'] = $order_info->confirm_time;
            $item['expressName'] = $order_info->shipping_name;
            if($order_info->shipping_name)
            {
                $express = OrderExpressListRepository::getInstance();
                $express_info = $express->getByName($order_info->shipping_name);
            }
            $item['expressCode'] = isset($express_info->code) ? $express_info->code : '';
            $item['shippingSn'] = $order_info->shipping_code;
            $item['timestamp'] = $order_info->created_at->toDateTimeString();

            $goods_info = $order_info->orderGoods[0];
            $goods_album = GoodsAlbumRepository::getInstance();
            $album = $goods_album->getInIds([$goods_info->goods_id]);
            $orderGoodses = [
                'id'=>$goods_info->id,
                'goodsId'=>$goods_info->goods_id,
                'name' => $goods_info->goods_name,
                'cash' => $goods_info->member_price,
                'number' => $goods_info->goods_num,
                'imagePath'=>isset($album[$goods_info->goods_id]) ? $album[$goods_info->goods_id] : ''
            ];
            $merchant = ['id'=>0,'name'=>"创客中心",'telephone'=>'',"orderGoodses"=>$orderGoodses];
            $item['merchant'] = $merchant;
            $address = ['name'=>$order_info->consignee,'mobile'=>$order_info->mobile,'street'=>$order_info->address];
            $item['address'] = $address;
        }
        return $item;
    }

    /**
     * API更新订单状态
     * @param QueryRequest $queryRequest
     * @param $user_id
     * @return int
     */
    public function updateStatus(QueryRequest $queryRequest,$user_id)
    {
        $status = [1=>4,2=>5];
        $order_info = OrderInfo::where('id',$queryRequest->id)->where("user_id",$user_id)->first();
        if(!$order_info)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '订单不存在',
            ]);
        }
        if($queryRequest->action == 1 && $order_info->status != 3)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '当前状态不可确认收货',
            ]);
        }
        if($queryRequest->action == 2 && $order_info->status != 1)
        {
            throw new ParamsException([
                'error_code' => '1000',
                'message'    => '当前状态不可取消订单',
            ]);
        }
        $set = ['status'=>$status[$queryRequest->action]];
        if($queryRequest->action == 1)
        {
            $set['confirm_time'] = date("Y-m-d H:i:s");
        }
        $res = $order_info->update($set);
        if($res && $queryRequest->action == 2)
        {
            $order_goods = OrderGoods::where('order_id',$queryRequest->id)->first();
            if($order_goods)
            {
                GoodsInfo::where('id',$order_goods->goods_id)->increment('stock',1);//增加当前产品库存
            }
        }
        return $res;
    }

    /**
     * 更新订单信息
     * @param $set
     * @param $id
     * @return bool
     */
    public function update($set,$id)
    {
        return OrderInfo::where('id',$id)->update($set);
    }

    /**
     *根据ID获取一条订单信息
     */
    public function getOneOrder($id)
    {
        return OrderInfo::where('id',$id)->first();
    }
}